package translinkApp.Data.ResolvedLocation;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

public class ResolvedLocationList extends ArrayList<ResolvedLocation> implements Serializable {

	private static final long serialVersionUID = 1L;
	ResolvedLocation lastPinned = null;

	@Override
	public boolean add(ResolvedLocation object) {

		int index = 0;

		Iterator<ResolvedLocation> iterator = this.iterator();
		while (iterator.hasNext()) {

			if (object.getDisplayAddress().compareToIgnoreCase(iterator.next().getDisplayAddress()) > 1) {
				index++;
			}

			if (object.isPinned()) {
				index = index - unpinnedCount();

				if (lastPinned != null) {
					if (object.getDisplayAddress().compareToIgnoreCase(
							lastPinned.getDisplayAddress()) > 1) {
						index++;
					}
				}

				lastPinned = object;
			}

		}

		if (index < 0) {
			index = 0;
		}

		add(index, object);
		return true;
	}

	public void sort() {
		Collections.sort(this, new Comparator<ResolvedLocation>() {

			@Override
			public int compare(ResolvedLocation object1, ResolvedLocation object2) {
				return object1.getDisplayAddress().compareToIgnoreCase(object2.getDisplayAddress());
			}

		});
	}

	private int unpinnedCount() {
		int counter = 0;
		Iterator<ResolvedLocation> iterator = this.iterator();
		while (iterator.hasNext()) {

			ResolvedLocation location = iterator.next();

			if (!location.isPinned()) {
				counter++;
			}

		}
		return counter;
	}

}
